package jsp;

import util.CookieUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 黄衡熙
 * @version 1.0
 * 用户登录功能
 * 当登录页面提交的时候访问该Servlet
 * 判断用户所输入的用户名与密码是否正确
 * 如果正确
 *  则将正确的用户名与密码保存到Cookie中
 *  且页面跳转到主页main.jsp
 * 如果不正确
 *  则页面跳转到登录页面login.jsp
 *  且在登录页面中显示错误消息:用户名或密码错误
 *  使用假数据,假设数据库中存在一个账号,用户名admin，密码123456
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
//    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        String username = req.getParameter("username");
//        String password = req.getParameter("password");
//         if ("admin".equals(username) && "123456".equals(password)){
//            Cookie cookie = new Cookie("username","admin");
//            Cookie cookie1 = new Cookie("password","123456");
//            cookie.setMaxAge(24*60*60);
//            cookie1.setMaxAge(24*60*60);
//            resp.addCookie(cookie);
//            resp.addCookie(cookie1);
//            req.getRequestDispatcher("/jsp/login.jsp").forward(req, resp);
//        }else{
//            req.setAttribute("loginMsg", "用户名或密码错误");
//            req.getRequestDispatcher("/jsp/main.jsp").forward(req, resp);
//        }
//
//    }
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // 获取用户在表单中输入的用户名与密码
    String username = req.getParameter("username");
    String password = req.getParameter("password");
    // 判断用户输入的用户名与密码是否正确
    if ("admin".equals(username) && "123456".equals(password)) {
        // 如果正确,将当前正确的用户名与密码保存到Cookie中,便于自动登录
//            CookieUtil.addCookie("username",username,resp);
//            CookieUtil.addCookie("password",password,resp);
        // 可以设置保存一天
        CookieUtil.addCookie("username", username, 24 * 60 * 60, resp);
        CookieUtil.addCookie("password", password, 24 * 60 * 60, resp);
        // 进入主页
        req.getRequestDispatcher("/jsp/main.jsp").forward(req, resp);
        return;
    }
    // 如果不正确,给出错误消息,并返回到登录页进行重新登录
    req.setAttribute("loginMsg", "用户名或密码错误");
    req.getRequestDispatcher("/jsp/login.jsp").forward(req, resp);
}
}
